package red.yancloud.www.ui.activity

import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_special_topic.*
import kotlinx.android.synthetic.main.activity_special_topic.back_iv
import kotlinx.android.synthetic.main.activity_special_topic.errorView
import kotlinx.android.synthetic.main.activity_special_topic.smartRefreshLayout
import kotlinx.android.synthetic.main.activity_special_topic.title_tv
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.SpecialTopic
import red.yancloud.www.internet.bean.TypeData
import red.yancloud.www.ui.adapter.TypeRecyclerAdapter
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.ui.adapter.SpecialTopicRecyclerAdapter
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/28 11:52
 * E_Mail：yh131412hys@163.com
 * Describe：红云专题
 * Change：
 * @Version：V1.0
 */
class SpecialTopicActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "SpecialTopicActivity"

    private var selectPosition = -1//用于记录用户选择的变量
    private var typeId=""
    private var keyword:String=""

    private lateinit var typeList:ArrayList<TypeData>
    private lateinit var mTypeAdapter : TypeRecyclerAdapter
    private lateinit var mAdapter: SpecialTopicRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.activity_special_topic

    override fun configViews() {
        super.configViews()

////        专题文汇
//        val doc = Jsoup.connect("http://www.yancloud.red/Subject/Index/index/p/1.html").get()
////			内容
//        val timeSelects = doc.select("div[class=main-wenhuicont]>ul>li")
//        for (elements in timeSelects) {
//
//            println(elements.select("a").select("img").attr("src") + "---" + elements.select("a").attr("href"))
//
//            val contentSelects = elements.select("div[class=box]")
//            println(contentSelects.select("p")[0].text() + "\n"
//                    + contentSelects.select("p")[1].select("a").attr("href") + "---" + contentSelects.select("p")[1].text() + "\n"
//                    + contentSelects.select("a").attr("href") + "---" + contentSelects.select("a").select("p").text() + "\n"
//                    + contentSelects.select("a").attr("href") + "---" + contentSelects.select("a")[2].text())
//            //				System.out.println(contentSelects.select("a").attr("href"));
//            //
//            //				System.out.println(contentSelects.select("a").text());
//            //				for (Element element : contentSelects) {
//            //					System.out.println(element.select("p").get(0).text());
//            //				}
//            Log.d(TAG,"---------------------------------------------------------------------------------------")
//        }

        title_tv.text="红云专题"
        back_iv.setOnClickListener(this)
        initSearchEditText()
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        specialTopicActivity_search_et.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId== EditorInfo.IME_ACTION_SEARCH) {

                    AppUtils.closeInoutDecorView(this@SpecialTopicActivity)
                    keyword = specialTopicActivity_search_et.text.toString().trim()
                    specialTopicActivity_search_et.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    page = 1
                    typeId = ""
                    selectPosition = -1
                    getRefreshDataList()
                    keyword=""
                    return true
                }
                return false
            }
        })
    }

    override fun initRecyclerView() {

        typeList = ArrayList()

        specialTopicActivity_type_rV.layoutManager= LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL,false)
        mTypeAdapter = TypeRecyclerAdapter(R.layout.item_read_type_list)
        specialTopicActivity_type_rV.adapter= mTypeAdapter
        mTypeAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                //获取选中的参数
                selectPosition = position
                mTypeAdapter.setSelectPosition(selectPosition)

                //                处理数据不刷新问题
                specialTopicActivity_type_rV.scrollBy(1,0)
                specialTopicActivity_type_rV.scrollBy(-1,0)
                page=1
                typeId = typeList[position].typeId
                getRefreshDataList()
            }
        }

        specialTopicActivity_rV.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        specialTopicActivity_rV.addItemDecoration(
            RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
        mAdapter= SpecialTopicRecyclerAdapter()
        specialTopicActivity_rV.adapter = mAdapter
        mAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                startActivity(
                    Intent(mContext, SpecialTopicContentActivity::class.java)
                        .putExtra("id", mAdapter.mData[position].id)
                        .putExtra("introduce", mAdapter.mData[position].introduce)
                )
            }
        })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> {

                finish()
            }
        }
    }

    override fun getRefreshDataList() {

        loadingDialog.show()

        RedCloudApis.getInstance().getSubject(page.toString(), limit, typeId, keyword, object : Observer<SpecialTopic> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: SpecialTopic) {

                if (t.code == Constants.SYSTEM_OK) {

                    if (t.data != null) {

                        if (t.data.menus != null && t.data.menus.size > 0) {

                            typeList.clear()
                            typeList.add(TypeData("全部",""))
                            for (i in 0 until t.data.menus.size) {

                                typeList.add(TypeData(t.data.menus[i].title, t.data.menus[i].id))
                            }

                            mTypeAdapter.data.clear()
                            mTypeAdapter.setSelectPosition(selectPosition)
                            mTypeAdapter.addData(typeList)
                            if (selectPosition == -1) {

                                specialTopicActivity_type_rV.scrollToPosition(0)
                            }
                        }

                        if (t.data.page != null && t.data.subjects != null && t.data.subjects.size > 0) {

                            totalPage = t.data.page.totalPage
                            errorView.visibility = View.GONE
                            smartRefreshLayout.visibility = View.VISIBLE
                            if (page == 1) {

                                specialTopicActivity_rV.scrollToPosition(0)
                                mAdapter.clear()
                                mAdapter.addData(t.data.subjects)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()

//                            处理数据加载后，页面刷新异常问题
                                specialTopicActivity_rV.scrollBy(1,0)
                                specialTopicActivity_rV.scrollBy(-1,0)
                            } else {

                                mAdapter.addData(t.data.subjects)
                                smartRefreshLayout.finishLoadMore()
                            }
                        } else {

                            if (page == 1) {

                                smartRefreshLayout.finishRefresh()

                                errorView.visibility = View.VISIBLE
                                smartRefreshLayout.visibility = View.GONE
                            } else {

                                ToastUtils.showToast(getString(R.string.data_all_load))
                                smartRefreshLayout.finishLoadMore()
                            }
                        }
                    }
                }else{

                    errorView.visibility = View.VISIBLE
                    smartRefreshLayout.visibility = View.GONE
                }

                loadingDialog.dismiss()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
                errorView.visibility = View.VISIBLE
                smartRefreshLayout.visibility = View.GONE
            }
        })
    }
}
